import React from 'react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeRaw from 'rehype-raw';
import rehypeSanitize from 'rehype-sanitize';
import rehypeSlug from 'rehype-slug';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';

interface MarkdownRendererProps {
    content: string;
    className?: string;
    isCompact?: boolean;
    maxHeight?: string;
}

const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({
    content,
    className = '',
    isCompact = false,
    maxHeight
}) => {
    // 确保表格能够正确渲染
    const fixTables = (content: string) => {
        // 检查是否存在可能被错误渲染的表格
        if (content.includes('|') && content.includes('\n')) {
            // 确保表格行之间有空行，有助于正确解析
            return content.replace(/((?:\|.+\|\r?\n)+)/g, (match) => {
                // 确保表格的分隔行格式正确
                if (!match.includes('| --- |') && !match.includes('|:---:|') && !match.includes('|:---')) {
                    const lines = match.split('\n');
                    let hasHeader = false;

                    // 查找可能的表头行
                    for (let i = 0; i < lines.length; i++) {
                        if (lines[i].includes('|') && i < lines.length - 1) {
                            // 在标题行后添加分隔行
                            const columnCount = (lines[i].match(/\|/g) || []).length - 1;
                            const separator = '|' + Array(columnCount).fill(' --- ').join('|') + '|';

                            // 仅当下一行不是分隔行时插入
                            if (i + 1 < lines.length && !lines[i + 1].includes('---')) {
                                lines.splice(i + 1, 0, separator);
                                hasHeader = true;
                                break;
                            }
                        }
                    }

                    // 如果没有找到表头，则在第一行后添加分隔行
                    if (!hasHeader && lines.length > 0 && lines[0].includes('|')) {
                        const columnCount = (lines[0].match(/\|/g) || []).length - 1;
                        const separator = '|' + Array(columnCount).fill(' --- ').join('|') + '|';
                        lines.splice(1, 0, separator);
                    }

                    return lines.join('\n') + '\n';
                }
                return match;
            });
        }
        return content;
    };

    return (
        <div
            className={`markdown-body prose ${isCompact ? 'compact' : ''} ${className} custom-scrollbar`}
            style={{
                maxHeight: maxHeight || 'none',
                overflow: maxHeight ? 'auto' : 'visible'
            }}
        >
            <ReactMarkdown
                remarkPlugins={[remarkGfm]}
                rehypePlugins={[
                    rehypeRaw,
                    rehypeSanitize,
                    rehypeSlug,
                    [rehypeAutolinkHeadings, { behavior: 'wrap' }]
                ]}
                components={{
                    a({ children, ...props }) {
                        return (
                            <span className="markdown-link" {...props}>
                                {children}
                            </span>
                        );
                    }
                }}
            >
                {fixTables(content)}
            </ReactMarkdown>
        </div>
    );
};

export default MarkdownRenderer; 